package cn.edu.gzhu.workOrderManagement.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import cn.hutool.json.JSONUtil;

@Configuration
@EnableCaching
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(connectionFactory);

        // Key序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        // Value序列化器使用 Hutool JSON 工具
        RedisSerializer<Object> hutoolJsonSerializer = new RedisSerializer<>() {
            @Override
            public byte[] serialize(Object value) {
                return JSONUtil.toJsonStr(value).getBytes();
            }

            @Override
            public Object deserialize(byte[] bytes) {
                if (bytes == null || bytes.length == 0) {
                    return null;
                }
                String json = new String(bytes);
                return JSONUtil.parse(json);
            }
        };

        redisTemplate.setValueSerializer(hutoolJsonSerializer);
        redisTemplate.setHashValueSerializer(hutoolJsonSerializer);

        return redisTemplate;
    }
}
